package com.xr.sunnyday.controller;

import com.xr.sunnyday.constant.MessageConstant;
import com.xr.sunnyday.constant.RedisMessageConstant;
import com.xr.sunnyday.entity.Result;
import com.xr.sunnyday.utils.SMSUtils;
import com.xr.sunnyday.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {


    @Autowired
    private JedisPool jedisPool;//获取链接池

    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        //
        Jedis jedis = jedisPool.getResource();
        //拼接手机号码
        String key = RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone;
        //获取验证码
        String codeInRedis = jedis.get(key);
        if (null==codeInRedis){
            //2.1生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //腾讯云需要String[]来替代短信模板的参数
            String[] params = new String[]{code+""};
            try {
                SMSUtils.sendSingleMessageForCode(telephone,params);
                jedis.setex(key,5*60,code+"");
                // 返回成功
                return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
            }catch (Exception e){
                e.printStackTrace();
                // 发送失败
                return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
            }
        }
        return new Result(false, "验证码已经发送了");
    }

    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){

        Jedis jedis = jedisPool.getResource();
        //定义一个key

        String key = RedisMessageConstant.SENDTYPE_LOGIN+"_"+telephone;

        //根据key获取redis中的验证码
        String codeInRedis = jedis.get(key);
        if (null==codeInRedis){
            //生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            try{
                //把验证码变成一个数组
                String[] params = new String[]{code+""};
                //使用腾讯云发送短信
                SMSUtils.sendSingleMessageForCode(telephone,params);
                //保存到redis
                jedis.setex(key,6*60,code+"");
                return new Result(true,"短信发送成功!");
            }catch (Exception e){
                return new Result(false,"短信发送失败！");
            }
        }
        //6.存在
        return new Result(false,"登录短信验证码已经发送了!!!");
    }

}
